package com.yingpai.fitness.dvp_2_0.main.activity.fitness;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.adpter.DynamicHotAndCityRecyclerAdapter;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.statusbar.Status;
import com.yingpai.fitness.dvp_2_0.main.activity.dynamic.DynamicDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.dynamic.PublishActivity;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.entity.dynamic.DynamicHotAndCityBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.yingpai.fitness.dvp_2_0.main.widget.CustomGridLayoutManage;
import com.yingpai.fitness.dvp_2_0.main.widget.ParentRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;


public class RunRideTopicDetailActivity extends CommonActivity implements RadioGroup.OnCheckedChangeListener, BaseQuickAdapter.OnItemChildClickListener, OnRefreshLoadMoreListener {


    @BindView(R.id.topic_detail_cover_iv)
    ImageView topicDetailCoverIv;
    @BindView(R.id.topic_detail_new_rb)
    RadioButton topicDetailNewRb;
    @BindView(R.id.topic_detail_rg)
    RadioGroup topicDetailRg;
    @BindView(R.id.topic_detail_parent_rv_list)
    ParentRecyclerView topicDetailParentRvList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.scrollView)
    NestedScrollView nestedScrollView;
    private DynamicHotAndCityRecyclerAdapter mAdapter;//热门的适配器/同城的适配器
    private String flag;
    private String linkurl;
    private int pageSize = 10;
    private int pageNum = 1;
    private TokenBean tokenBean;
    private int orderClause = 1;
    private DynamicHotAndCityBean mDynamicHotAndCityBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.CONTENT_INVASION_STATUS);
        setContentView(R.layout.run_ride_topic_detail_activity);
    }

    private void requestData(int mPageNum, int orderClause) {
        showDialog(this,null);
        finalOkGo.request(RequestType.GET, Contacts.HOST_SERVER + linkurl
                + "&&customerId=" + tokenBean.getId() + "&&orderClause="
                + orderClause + "&&pageNum=" + mPageNum + "&&pageSize="
                + pageSize, null, linkurl, new Callback<DynamicHotAndCityBean>() {
            @Override
            public void onSuccess(DynamicHotAndCityBean dynamicHotAndCityBean) {
                if (dynamicHotAndCityBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    mDynamicHotAndCityBean = dynamicHotAndCityBean;
                    Glide.with(context)
                            .load(dynamicHotAndCityBean.getMap().getThemeCategory().getPhotoUrl())
                            .placeholder(R.mipmap.default_small_bg)
                            .error(R.mipmap.default_small_bg)
                            .into(topicDetailCoverIv);

                    if (pageNum - 1 == 1) {
                        mAdapter.setNewData(dynamicHotAndCityBean.getMap().getPageInfo().getList());
                    } else {
                        mAdapter.addData(dynamicHotAndCityBean.getMap().getPageInfo().getList());
                    }
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    mAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (dynamicHotAndCityBean.getMap().getPageInfo().getTotal() % pageSize == 0) {
                        pagecount = dynamicHotAndCityBean.getMap().getPageInfo().getTotal() / pageSize;
                    } else {
                        pagecount = dynamicHotAndCityBean.getMap().getPageInfo().getTotal() / pageSize + 1;
                    }
                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }
                } else {
                    showToast(dynamicHotAndCityBean.getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            //最热
            case R.id.topic_detail_new_rb:
                orderClause = 1;
                break;
            //最新
            case R.id.topic_detail_hot_rb:
                orderClause = 2;
                break;
        }
        pageNum = 1;
        requestData(pageNum++, orderClause);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void initView() {
        final int startColor = ContextCompat.getColor(this, R.color.colorPrimary);
        final int endColor = ContextCompat.getColor(this, R.color.colorNavigation);

        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int headerHeight = topicDetailCoverIv.getHeight();
                int scrollDistance = Math.min(scrollY, headerHeight);
                float fraction = (float) scrollDistance / (float) headerHeight;
                int statusAlpha = (int) ((float) scrollDistance / (float) headerHeight * 255F);

                Status.with(RunRideTopicDetailActivity.this).statusBarBackgroundAlpha(statusAlpha);
                setNavigationViewColor(evaluate(fraction, endColor, startColor));
            }
        });

        EventBus.getDefault().register(this);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            flag = bundle.getString("flag");
            if (flag.equals("home")) {
                linkurl = bundle.getString("linkurl");
            }
        }

        topicDetailRg.setOnCheckedChangeListener(this);//设置监听

        topicDetailParentRvList = findViewById(R.id.topic_detail_parent_rv_list);//话题列表
        topicDetailParentRvList.setLayoutManager(new CustomGridLayoutManage(getApplicationContext(), 2));

        mAdapter = new DynamicHotAndCityRecyclerAdapter(R.layout.dynamic_hot_city_list_item);   //初始化适配器
        topicDetailParentRvList.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(this);//列表监听
    }

    @Override
    protected void initData() {
        pageNum = 1;
        requestData(pageNum++, orderClause);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(String messageEvent) {
        if ("点赞成功".equals(messageEvent)) {
            pageNum = 1;
            requestData(pageNum++, orderClause);
        } else if ("topic_success".equals(messageEvent)) {
            pageNum = 1;
            requestData(pageNum++, orderClause);
        }
    }

    @Override
    @OnClick({R.id.topic_detail_publish_btn})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.topic_detail_publish_btn:
                Bundle bundle = new Bundle();
                bundle.putInt("categoryId", mDynamicHotAndCityBean.getMap().getThemeCategory().getId());
                bundle.putString("categoryName", mDynamicHotAndCityBean.getMap().getThemeCategory().getCategoryName());
                bundle.putString("flag", "topic");
                startActivity(PublishActivity.class, bundle);
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestData(pageNum++, orderClause);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        requestData(pageNum++, orderClause);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        Bundle bundle = new Bundle();
        bundle.putInt("isPraised", mAdapter.getItem(position).getIsPraised());
        bundle.putInt("id", mAdapter.getItem(position).getId());
        startActivity(DynamicDetailActivity.class, bundle);
    }
}
